from webdav4.client import Client
from queue import Queue


class JGWebdav:
    """ 坚果云操作类 """

    def __init__(self, username, password, folder_name="pyqt-note"):
        # 异常收集队列
        self.except_queue = Queue()
        self.folder_name = folder_name
        self.client = Client(
            base_url="https://dav.jianguoyun.com/dav/", auth=(username, password))

    # 获取笔记本列表数据
    def cloud_notebooks(self):
        """ 获取笔记本列表数据 """

        ns = self.client.ls(self.folder_name, detail=False)
        notebooks = []
        if ns is not None and len(ns) > 0:
            for n in ns:
                notebooks.append(n[n.index("/") + 1:])

        return notebooks

    # 获取笔记列表数据
    def cloud_notes(self, notebook_name):
        """ 获取笔记列表数据 """

        ns = self.client.ls(f"{self.folder_name}/{notebook_name}", detail=False)
        notes = []
        if ns is not None and len(ns) > 0:
            for n in ns:
                # notes.append(n[n[::-1].index("/") - 2:])
                notes.append(n)
        return notes

    # 创建云端笔记本文件夹
    def create_cloud_notebook(self, notebook_name):
        """ 创建云端笔记本文件夹 """

        ndir = f"{self.folder_name}/{notebook_name}"
        try:
            self.client.mkdir(ndir)
        except:
            self.except_queue.put("创建云端笔记本文件夹异常")

    # 删除云端笔记本文件夹
    def delete_cloud_notebook(self, notebook_name):
        """ 删除云端笔记本文件夹 """

        ndir = f"{self.folder_name}/{notebook_name}"
        # # 重复请求显得不那么高效，注释掉
        # if self.client.exists(ndir):
        #     try:
        #         self.client.remove(ndir)
        #     except:
        #         self.except_queue.put("删除云端笔记本文件夹异常")

        try:
            self.client.remove(ndir)
        except:
            self.except_queue.put("删除云端笔记本文件夹异常")

    # 上传笔记到云端
    def upload_note_to_cloud(self, note_path, notebook_name, note_name):
        """ 上传笔记到云端 """

        file = f"{self.folder_name}/{notebook_name}/{note_name}.md"
        try:
            self.client.upload_file(note_path, file, overwrite=True)
        except:
            self.except_queue.put("上传笔记到云端异常")

    # 下载笔记到本地
    def download_note_to_local(self, cloud_note, note_save_path):
        """ 下载笔记到本地 """

        self.client.download_file(cloud_note, note_save_path)

    # 删除云端笔记
    def delete_cloud_note(self, notebook_name, note_name):
        """ 删除云端笔记 """

        file = f"{self.folder_name}/{notebook_name}/{note_name}.md"
        # # 重复请求显得不那么高效，注释掉
        # if self.client.exists(file):
        #     try:
        #         self.client.remove(file)
        #     except:
        #         self.except_queue.put("删除云端笔记异常")

        try:
            self.client.remove(file)
        except:
            self.except_queue.put("删除云端笔记异常")
